package org.liang.family_manager.controller;

import lombok.AllArgsConstructor;
import org.liang.family_manager.dao.po.FamilyMember;
import org.liang.family_manager.dao.po.MemberRelation;
import org.liang.family_manager.dao.repo.FamilyAdminRepository;
import org.liang.family_manager.dao.repo.FamilyMemberRepository;
import org.liang.family_manager.dao.repo.MemberRelationRepository;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("/api/family")
public class FamilyApiController {
    private final FamilyMemberRepository familyMemberRepository;
    private final FamilyAdminRepository familyAdminRepository;
    private final MemberRelationRepository memberRelationRepository;

    @GetMapping("/graph")
    public ResponseEntity<Map<String, Object>> getFamilyGraph(Authentication authentication) {
        // 1. 获取当前家族ID
        String username = authentication.getName();
        Long familyId = familyAdminRepository.findByUsername(username)
            .orElseThrow()
            .getId();
        
        // 2. 获取成员和关系
        List<FamilyMember> members = familyMemberRepository.findByFamilyId(familyId);
//        members.forEach(r->{
//            List<MemberRelation> byFromMemberId = memberRelationRepository.findByFromMemberId(r.getId());
//            r.setRelations(byFromMemberId);
//        });
        List<MemberRelation> relations = memberRelationRepository.findByFamilyId(familyId);
        // 3. 构建返回数据
        Map<String, Object> response = new HashMap<>();
        response.put("members", members);
        response.put("relations",relations);
        
        return ResponseEntity.ok(response);
    }
}